package repositories

import (
	"errors"
	"fox/db"
	"fox/models"
	request2 "fox/request"
	response2 "fox/response"
	"gorm.io/gorm"
	"math"
)

type RolePermissionRepository struct {
}

func NewRolePermissionRepository() (rolePermissionRepository *RolePermissionRepository) {
	return &RolePermissionRepository{}
}

func (repository *RolePermissionRepository) InsertRolePermission(rolePermission *models.RolePermission) (id int64, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Create(rolePermission)
	if result.RowsAffected == 1 {
		return rolePermission.ID, err
	}
	return 0, result.Error
}

func (repository *RolePermissionRepository) DeleteRolePermissionById(id int64) (err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Delete(&models.RolePermission{ID: id})
	if result.RowsAffected == 1 && result.Error == nil {
		return err
	}
	return result.Error
}

func (repository *RolePermissionRepository) UpdateRolePermissionById(rolePermission *models.RolePermission) (newRolePermission *models.RolePermission, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Model(&models.RolePermission{ID: rolePermission.ID}).UpdateColumns(rolePermission)
	result.Scan(&newRolePermission)
	return newRolePermission, result.Error

}

func (repository *RolePermissionRepository) SelectRolePermissionById(id int64) (rolePermission *models.RolePermission, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Where("id = ?", id).First(&rolePermission)
	if result.RowsAffected == 1 {
		return rolePermission, nil
	}
	if result.RowsAffected == 0 {
		return nil, errors.New("没有查找到记录")
	}
	return rolePermission, result.Error
}

func (repository *RolePermissionRepository) SelectUserRoles(rolePermission *request2.RolePermission) (result *response2.Result, err error) {
	var (
		offset              int
		rolePermissions     *[]models.RolePermission
		countRolePermission *models.RolePermission
		count               int64
		totalPage           int
	)
	countRolePermission = new(models.RolePermission)
	count = repository.CountUserRoles(countRolePermission)
	if count == 0 {
		result.Total = 0
		result.Size = rolePermission.Size
		result.Page = rolePermission.Page
		result.Lists = make([]interface{}, 0)
		return result, err
	}

	totalPage = int(math.Ceil(float64(count) / float64(rolePermission.Size)))
	offset = (rolePermission.Page - 1) * rolePermission.Size
	db.GDatabase.Db.Scopes(request2.Paginate(offset, rolePermission.Size)).Model(&models.RolePermission{}).Order(rolePermission.SortField + " " + rolePermission.Sort).Find(&rolePermissions)
	return &response2.Result{
		Total:     count,
		TotalPage: totalPage,
		Page:      rolePermission.Page,
		Size:      rolePermission.Size,
		Lists:     rolePermissions,
	}, err
}

func (repository *RolePermissionRepository) CountUserRoles(rolePermission *models.RolePermission) (count int64) {

	db.GDatabase.Db.Model(&models.RolePermission{}).Count(&count)
	return count
}
